package com.open.capacity.task.service.impl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.open.capacity.common.exception.service.ServiceException;
import com.open.capacity.common.util.PageUtil;
import com.open.capacity.common.web.CodeEnum;
import com.open.capacity.common.web.PageResult;
import com.open.capacity.common.web.Result;
import com.open.capacity.task.dao.TaskTypeDao;
import com.open.capacity.task.model.TaskType;
import com.open.capacity.task.service.TaskTypeService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.collections.MapUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Map;

@Slf4j
@Service
public class TaskTypeServiceImpl implements TaskTypeService {

    @Autowired
    TaskTypeDao taskTypeDao;

    /**
     * 根据传过来的条件查询任务类型的相关信息
     *
     * @param params
     * @return
     * @throws ServiceException
     */
    @Override
    public PageResult<TaskType> getTaskType(Map<String, Object> params) throws ServiceException {
        try {
            PageHelper.startPage(MapUtils.getInteger(params, PageUtil.PAGE), MapUtils.getInteger(params, PageUtil.LIMIT));
            PageInfo<TaskType> info = new PageInfo<>(this.taskTypeDao.getTaskType(params));
            return PageResult.<TaskType>builder()
                    .data(info.getList())
                    .code(CodeEnum.SUCCESS.getCode())
                    .count(info.getTotal())
                    .build();
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public Result add(TaskType taskType) {
        try {
            int result = taskTypeDao.add(taskType);
            return result == 0 ? Result.failed("添加失败"):Result.succeed("添加成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public Result del(String id) {
        try {
            int result = taskTypeDao.del(id);
            return result == 0 ? Result.failed("删除失败"):Result.succeed("删除成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }

    @Override
    public Result edit(TaskType taskType) {
        try {
            int result = taskTypeDao.edit(taskType);
            return result == 0 ? Result.failed("编辑失败"):Result.succeed("编辑成功");
        } catch (Exception e) {
            log.debug(e.getMessage());
            throw new ServiceException(e);
        }
    }
}
